package com.hyopt.modules.app.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hyopt.common.utils.Constant;
import com.hyopt.common.utils.UUIDUtils;
import com.hyopt.modules.app.dao.AlarmInfoDao;
import com.hyopt.modules.app.entity.AlarmInfoEntity;
import com.hyopt.modules.app.entity.AlarmPhotoEntity;
import com.hyopt.modules.app.entity.SysDictionaryEntity;
import com.hyopt.modules.app.form.*;
import com.hyopt.modules.app.service.AlarmInfoService;
import com.hyopt.modules.app.service.AlarmPhotoService;
import com.hyopt.modules.app.service.SysDictionaryService;
import com.hyopt.modules.app.utils.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @author liubin
 * @date 2020/1/6 10:54
 */
@Service
public class AlarmInfoServiceImpl extends ServiceImpl<AlarmInfoDao, AlarmInfoEntity> implements AlarmInfoService {
  @Autowired
  private AlarmPhotoService alarmPhotoService;
  @Autowired
  private SysDictionaryService sysDictionaryService;

  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean save(AlarmSaveForm form) throws Exception {
    AlarmInfoEntity alarmInfoEntity = new AlarmInfoEntity();
    BeanUtils.copyProperties(form, alarmInfoEntity);

    if (ObjectUtil.isNotNull(form.getPhoto())) {
      AlarmPhotoEntity a = new AlarmPhotoEntity();
      a.setAlarmId(form.getId());
      a.setCameraUID(0);
      a.setWriter("abc");
      a.setWriteDate(new Date().getDate());
      a.setPhotoType(1);
      for (AlarmPhotoEntity alarmPhotoEntity : form.getPhoto()) {
        a.setId(UUIDUtils.getUUIDInOrderId());
        a.setPhoto(alarmPhotoEntity.getPhoto());
        if (!alarmPhotoService.savePhotoSelective(a)) {
          return false;
        }
      }
    }

    //报警处理结果
    /*SysDictionaryEntity sysDictionaryEntity = sysDictionaryService.getBaseMapper()
      .selectOne(new QueryWrapper<SysDictionaryEntity>()
        .eq("Keywords", "alarm_operate_type")
        .eq("value", form.getAlarmOperateType()));*/
    alarmInfoEntity.setOperateResult(form.getAlarmOperateType());
    alarmInfoEntity.setAlarmStatus(0);
    alarmInfoEntity.setOperateDate(new Date());
    alarmInfoEntity.setOperator(form.getUid().toString());
    if (this.baseMapper.updateById(alarmInfoEntity) == 0) {
      return false;
    }
    return true;
  }

  //当前--不分页，去重，未处理的所有
  @Override
  public List<AlarmListInfoVo> getNowList(AlarmNowQueryForm form) throws Exception {
    List<AlarmListInfoVo> result = this.baseMapper.getNowList(form);
    if (CollUtil.isNotEmpty(result)) {
      //去重算法
      List<AlarmListInfoVo> selectOptionResult = SelectOption(result);
      return selectOptionResult;
    }
    return result;
  }

  //已处理未处理--分页，不去重，未处理
  @Override
  public List<AlarmListInfoVo> getHandleList(AlarmHandledQueryForm form) throws Exception {
    List<AlarmListInfoVo> result;
    if(form.getAlarmStatus() == 1){
      result = this.baseMapper.getUnHandleList(form);
    }else{
      result = this.baseMapper.getHandleList(form);
    }
    if (CollUtil.isNotEmpty(result)) {
      //切割數據
      //从第几条数据开始
      int firstIndex = (form.getPage() - 1) * form.getSize();
      //到第几条数据结束
      int lastIndex = form.getPage() * form.getSize();
      if (result.size() < lastIndex) {
        lastIndex = result.size();
      }
      if(firstIndex>result.size()){
        return null;
      }
      result = result.subList(firstIndex, lastIndex);
      for (AlarmListInfoVo vo : result) {
        List<AlarmPhotoEntity> list = alarmPhotoService.list(new QueryWrapper<AlarmPhotoEntity>()
          .eq("PhotoType", 0)
          .eq("AlarmId", vo.getId()));
        vo.setAlarmPhoto(list);
      }

    }
    return result;
  }

  //已处理未处理--不分页，不去重，未处理
  @Override
  public List<AlarmListInfoVo> getAllNumber(AlarmHandledQueryForm form) throws Exception {
    List<AlarmListInfoVo> result = this.baseMapper.getAllNumber(form);
    return result;
  }
  //统计--7天，不去重，分页
  @Override
  public List<AlarmListInfoVo> totalList(AlarmListQueryForm form) throws Exception {
    List<AlarmListInfoVo> result = this.baseMapper.totalList(form);
    if (CollUtil.isNotEmpty(result)) {
      //切割數據
      //从第几条数据开始
      int firstIndex = (form.getPage() - 1) * form.getSize();
      //到第几条数据结束
      if(firstIndex>result.size()){
        return null;
      }
      int lastIndex = form.getPage() * form.getSize();
      if (result.size() < lastIndex) {
        lastIndex = result.size();
      }

      result = result.subList(firstIndex, lastIndex);
      for (AlarmListInfoVo vo : result) {
        List<AlarmPhotoEntity> list = alarmPhotoService.list(new QueryWrapper<AlarmPhotoEntity>()
          .eq("PhotoType", 0)
          .eq("AlarmId", vo.getId()));
        vo.setAlarmPhoto(list);
      }

    }
    return result;
  }

  @Override
  public int getTotal(AlarmListQueryForm form) throws Exception {
    List<AlarmListInfoVo> result = this.baseMapper.totalList(form);
    return result.size();
  }

  private List<AlarmListInfoVo> SelectOption(List<AlarmListInfoVo> result) {
    HashSet<Integer> temp = new HashSet<>();
    for (int i = 0; i < result.size(); i++) {
      //如果该元素已经是重复的不再遍历比较
      if(!temp.contains(result.get(i).getId())) {
        for (int j = i + 1; j < result.size(); j++) {
          if (result.get(i).getLatitude().compareTo(result.get(j).getLatitude()) == 0 &&
            result.get(i).getLongitude().compareTo(result.get(j).getLongitude()) == 0) {
            temp.add(result.get(j).getId());
            if (result.get(i).getCount() == 0) {
              result.get(i).setCount(2);
            } else {
              result.get(i).setCount(result.get(i).getCount() + 1);
            }
          }
        }
      }
    }


    Iterator<AlarmListInfoVo> iterator = result.iterator();
    while (iterator.hasNext()) {
      AlarmListInfoVo obj = iterator.next();
      if (temp.contains(obj.getId())) {
        iterator.remove();
      }
    }
    return result;
  }

  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean listClear(AlarmClearForm form) {
    Map<String, Object> map = new HashMap<>(16);
    map.put("list", form.getID());
    map.put("status", Constant.AlarmStatus.HANDLED.getValue());
    map.put("operateResult", form.getAlarmOperateType());
    if (StringUtils.isNotBlank(form.getOperateDesc())) {
      map.put("operateDesc", form.getOperateDesc());
    }
    if (this.baseMapper.updateBatch(map)) {
      return true;
    }
    return false;
  }

  @Override
  public AlarmListInfoVo getDetail(Integer alarmId) {
    AlarmListInfoVo vo = this.baseMapper.getDetail(alarmId);
    List<AlarmPhotoEntity> alarmPhoto = alarmPhotoService.getBaseMapper()
      .selectList(new QueryWrapper<AlarmPhotoEntity>()
        .eq("AlarmId", alarmId).eq("PhotoType", 0));
    vo.setAlarmPhoto(alarmPhoto);
    List<AlarmPhotoEntity> photo = alarmPhotoService.getBaseMapper()
      .selectList(new QueryWrapper<AlarmPhotoEntity>()
        .eq("AlarmId", alarmId).eq("PhotoType", 1));
    vo.setPhoto(photo);
    //报警类型
    vo.setAlarmType(sysDictionaryService.getBaseMapper().selectOne(new QueryWrapper<SysDictionaryEntity>()
      .eq("Keywords", "alarm_type")
      .eq("value", vo.getAlarmCode()))
      .getDescription());
    vo.setId(alarmId);
    if(vo.getOperateResult() != null){
        vo.setOperateType(sysDictionaryService.getBaseMapper().selectOne(new QueryWrapper<SysDictionaryEntity>()
                .eq("Keywords", "alarm_operate_type")
                .eq("value", vo.getOperateResult()))
                .getDescription());
    }
    return vo;
  }

  @Override
  public Map<String, String> getUserTokenByAlarmId(String ids) {
    Map<String, String> result = new HashMap<>();
    List list = this.baseMapper.getUserTokenByAlarmId(ids.split(","));
    if (list != null && list.size() > 0) {
      Set<String> result1 = new HashSet();
      Set<String> result2 = new HashSet();
      for (int i = 0; i < list.size(); i++) {
        Map map = (Map) list.get(i);
        if (map != null) {
          System.out.println(map.get("Token").toString().trim().length());
          if (map.get("Token").toString().trim().length() == 44) {
            result1.add(map.get("Token").toString().trim());
          } else if (map.get("Token").toString().trim().length() == 64) {
            result2.add(map.get("Token").toString().trim());
          }
        }
      }
      if (!result1.isEmpty()) {
        result.put("and", String.join(",", new ArrayList<>(result1)));
      }
      if (!result2.isEmpty()) {
        result.put("ios", String.join(",", new ArrayList<>(result2)));
      }
    }
    return result;
  }

}
